战争中保持各个城市间的连通性非常重要。本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报。注意:若该国本来就不完全连通,是分裂的k个区域,而失去一个城市并不改变其他城市之间的连通性,则不要发出警报。

输入格式:

输入在第一行给出两个整数N(0 < N ≤ 500)和M(≤ 5000),分别为城市个数(于是默认城市从0到N-1编号)和连接两城市的通路条数。随后M行,每行给出一条通路所连接的两个城市的编号,其间以1个空格分隔。在城市信息之后给出被攻占的信息,即一个正整数K和随后的K个被攻占的城市的编号。

注意:输入保证给出的被攻占的城市编号都是合法的且无重复,但并不保证给出的通路没有重复。

输出格式:

对每个被攻占的城市,如果它会改变整个国家的连通性,则输出Red Alert: City k is lost!,其中k是该城市的编号;否则只输出City k is lost.即可。如果该国失去了最后一个城市,则增加一行输出Game Over.

输入样例:

1
2
3
4
5
6
7
5 4
0 1
1 3
3 0
0 4
5
1 2 0 4 3

输出样例:

1
2
3
4
5
6
City 1 is lost.
City 2 is lost.
Red Alert: City 0 is lost!
City 4 is lost.
City 3 is lost.
Game Over.

思路

这道题第一眼看上去,以为是跑一遍tarjan求割点就Over了,但是写完交上去就只得了15分,看来没这么简单,仔细读了读题之后,按照题目要求只能采用在线做法,每次更新连通块的数目,本题解采用DFS求连通块数目。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 510;
int w[maxn][maxn];
bool st[maxn];
int n, m;
void dfs(int u)
{
st[u] = 1;
for(int i = 0; i < n; i ++){
if(w[u][i] && !st[i]){
dfs(i);
}
}
}
int get_num()
{
int res = 0;
memset(st, 0, sizeof st);
for(int i = 0; i < n; i ++){
if(!st[i]){
res ++;
dfs(i);
}
}
return res;
}
int main()
{
cin >> n >> m;
for(int i = 0; i < m; i ++){
int a, b;
cin >> a >> b;
w[a][b] = w[b][a] = 1;
}
int cnt0 = get_num();
int k;
cin >> k;
for(int i = 0; i < k; i ++){
int x; cin >> x;
for(int i = 0; i < n; i ++){
w[i][x] = w[x][i] = 0;
}
int cnt = get_num();
if(cnt > cnt0 + 1) printf("Red Alert: City %d is lost!\n", x);
else printf("City %d is lost.\n", x);
cnt0 = cnt;
if(i == n - 1) cout << "Game Over." << endl;
}
return 0;
}